package com.github.anastr.speedviewlib.util;
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import ohos.aafwk.ability.fraction.Fraction;
import ohos.agp.text.Font;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ResUtil {

    //把resId转成color int
    public static int getColor(Context context, int resId) {
        try {
            context = getSateContext(context);
            return context.getResourceManager().getElement(resId).getColor();
//            return context.getColor(resId);//在tv上报错java.lang.NoSuchMethodError: No interface method getColor(I)
        } catch (Exception ignore) {
        }
        return -1;
    }

    //Fraction需要特殊处理
    public static Context getSateContext(Context context) {
        if (context instanceof Fraction) {
            Fraction fraction = (Fraction) context;
            return fraction.getFractionAbility().getContext();
        }
        return context;
    }


    public static PixelMap getPixelMap(Context context, int resource) {
        PixelMap pixelmap = null;
        try {
            Resource resourceObject = context.getResourceManager().getResource(resource);
            ImageSource imageSource = ImageSource.create(resourceObject, null);
            ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
            pixelmap = imageSource.createPixelmap(decodingOpts);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        return pixelmap;
    }

    public static PixelMap getPixelMap(Context context, int resource, int width, int height) {
        PixelMap pixelmap = null;
        try {
            Resource resourceObject = context.getResourceManager().getResource(resource);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            ImageSource imageSource = ImageSource.create(resourceObject, sourceOptions);
            ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
            Size size = new Size(width, height);
            decodingOpts.desiredSize = size;
            pixelmap = imageSource.createPixelmap(decodingOpts);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        return pixelmap;
    }

    public static int[] To_RGB(int color) {
        int red = (color & 0xff0000) >> 16;
        int green = (color & 0x00ff00) >> 8;
        int blue = (color & 0x0000ff);
        return new int[]{red, green, blue};
    }

    /**
     * Return the red component of a color int. This is the same as saying
     * (color >> 16) & 0xFF
     */
    public static int red(int color) {
        return (color >> 16) & 0xFF;
    }

    /**
     * Return the green component of a color int. This is the same as saying
     * (color >> 8) & 0xFF
     */
    public static int green(int color) {
        return (color >> 8) & 0xFF;
    }

    /**
     * Return the blue component of a color int. This is the same as saying
     * color & 0xFF
     */
    public static int blue(int color) {
        return color & 0xFF;
    }


    /**
     * 获取字体 根目录：resources/rawfile/
     *
     * @param context
     * @param typefaceName
     * @return
     */
    public static Font getFont(Context context, String typefaceName) {
        if (TextTool.isNullOrEmpty(typefaceName)) {
            return null;
        }
        StringBuffer fileName = new StringBuffer(typefaceName);
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), fileName.toString());
//        File file = new File(context.getCodeCacheDir(), fileName.toString());
        OutputStream outputStream = null;
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/fonts/" + typefaceName);
        Resource resource = null;
        try {
            resource = rawFileEntry.openRawFile();
            outputStream = new FileOutputStream(file);
            int index;
            byte[] bytes = new byte[1024];
            if (resource != null) {
                while ((index = resource.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, index);
                    outputStream.flush();
                }

                Font.Builder builder = new Font.Builder(file);
                Font font = builder.build();
                return font;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            //e?.printStackTrace();
        } finally {
            try {
                if (resource != null)
                    resource.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
